package com.iflytek.elpmobile.utils;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;

public class MD5Utils {

	/**
	 * @param file
	 * @return String md5 value
	 * @throws IOException
	 * @author jgzheng 2014-11-11
	 */
	public static String MD5(File file){
		if(!file.exists()){
			return "";
		}
		String catchString="";
		byte[] buffer = null;
		MessageDigest md5 = null;
		try {
			FileInputStream fis=new FileInputStream(file);
			int len=(int)file.length();
			byte[] temp = new byte[1024];
			buffer = new byte[len];
			int size = 0;
			int defaultStart=0;
			while ((size = fis.read(temp)) != -1) {
				System.arraycopy(temp,0,buffer,defaultStart,size);
				defaultStart+=size;
			}
			fis.close();
			md5 = MessageDigest.getInstance("MD5");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			catchString=e.toString();
			return "";
		}catch (IOException e) {
			e.printStackTrace();
			catchString=e.toString();
			return "";
		}catch (Exception e) {
			e.printStackTrace();
			catchString=e.toString();
			return "";
		}

		byte[] md5Bytes = md5.digest(buffer);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}
}
